<!-- src/views/health/Disease.vue（示例路径） -->
<script setup lang="ts">
import { ref, onMounted, computed } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"

import { listPets } from "@/api/pets"
import { addHealthDisease, deleteHealthDisease, emptyHealthDisease, listHealthDisease, updateHealthDisease, type HealthDisease } from "@/api/health_disease"

/** 宠物列表 & 当前宠物 */
const pets = ref<any[]>([])
const currentPetId = ref<number | null>(null)

const diseaseList = ref<HealthDisease[]>([])
const loading = ref(false)

/** 弹窗控制 */
const addDialog = ref(false)
const editDialog = ref(false)

/** 表单 */
const form = ref<HealthDisease>(emptyHealthDisease())

/** 严重程度选项 */
const severityOptions = [
    { value: 1, label: "轻微" },
    { value: 2, label: "中等" },
    { value: 3, label: "严重" }
]

/** 当前选中宠物（用于卡片展示） */
const currentPet = computed(() => {
    return pets.value.find(p => p.id === currentPetId.value) || null
})

/** 严重程度转标签类型 */
const severityTagType = (sev: number | null | undefined) => {
    if (sev === 3) return "danger"
    if (sev === 2) return "warning"
    return "success"
}

/** 严重程度显示文本 */
const severityLabel = (sev: number | null | undefined) => {
    return severityOptions.find(s => s.value === sev)?.label ?? "-"
}

/** 加载宠物列表 */
const loadPets = async () => {
    const res = await listPets({ pageNum: 1, pageSize: 100 })
    pets.value = res.data.list || []
    if (pets.value.length > 0 && !currentPetId.value) {
        currentPetId.value = pets.value[0].id
    }
}

/** 加载病情记录列表 */
const loadDiseaseList = async () => {
    if (!currentPetId.value) return
    loading.value = true
    const res = await listHealthDisease(currentPetId.value)
    diseaseList.value = res.data || []
    loading.value = false
}

/** 切换宠物 */
const changePet = (id: number) => {
    currentPetId.value = id
    loadDiseaseList()
}

/** 打开新增 */
const openAdd = () => {
    form.value = emptyHealthDisease()
    // 绑定当前宠物
    form.value.petId = currentPetId.value
    addDialog.value = true
}

/** 保存新增 */
const saveAdd = async () => {
    if (!form.value.petId) {
        form.value.petId = currentPetId.value
    }

    const res = await addHealthDisease(form.value)
    if (res.code === 200) {
        ElMessage.success("添加成功")
        addDialog.value = false
        await loadDiseaseList()
    } else {
        ElMessage.error(res.msg)
    }
}

/** 打开编辑 */
const openEdit = (row: HealthDisease) => {
    form.value = { ...row }
    editDialog.value = true
}

/** 保存编辑 */
const saveEdit = async () => {
    const res = await updateHealthDisease(form.value)
    if (res.code === 200) {
        ElMessage.success("修改成功")
        editDialog.value = false
        await loadDiseaseList()
    } else {
        ElMessage.error(res.msg)
    }
}

/** 删除记录 */
const removeRecord = (row: HealthDisease) => {
    ElMessageBox.confirm("确定删除该病情记录吗？", "提示", { type: "warning" })
        .then(async () => {
            const res = await deleteHealthDisease(row.id!, currentPetId.value!)
            if (res.code === 200) {
                ElMessage.success("删除成功")
                await loadDiseaseList()
            } else {
                ElMessage.error(res.msg)
            }
        })
}

onMounted(async () => {
    await loadPets()
    await loadDiseaseList()
})
</script>

<template>
    <div class="page">

        <!-- 顶部：宠物下拉选择 -->
        <div class="pet-selector-row">
            <el-select v-model="currentPetId" filterable placeholder="选择宠物" @change="changePet" style="width: 260px">
                <el-option v-for="p in pets" :key="p.id" :value="p.id" :label="p.name">
                    <div class="option-item">
                        <img :src="p.avatar" class="option-avatar" />
                        <span>{{ p.name }}</span>
                    </div>
                </el-option>
            </el-select>
        </div>

        <!-- 标题 + 当前宠物卡片 + 新增按钮 -->
        <div class="header">
            <div class="header-left">
                <div>
                    <span class="title">病情记录</span>
                </div>

                <div v-if="currentPet" class="current-pet-card">
                    <img :src="currentPet.avatar" class="card-avatar" />
                    <div class="card-text">
                        <div class="card-name">{{ currentPet.name }}</div>
                        <div class="card-sub">健康情况一目了然</div>
                    </div>
                </div>
            </div>

            <div style="align-self: start;">
                <el-button type="primary" class="add-record" @click="openAdd">
                    新增记录
                </el-button>
            </div>

        </div>

        <!-- 列表 -->
        <el-table :data="diseaseList" v-loading="loading" border>
            <el-table-column prop="diseaseName" label="疾病名称" min-width="160" />
            <el-table-column label="起止日期" min-width="220">
                <template #default="{ row }">
                    <span>{{ row.startDate }}</span>
                    <span v-if="row.endDate"> ~ {{ row.endDate }}</span>
                    <span v-else class="ongoing-tag">（未结束）</span>
                </template>
            </el-table-column>
            <el-table-column label="严重程度" width="120">
                <template #default="{ row }">
                    <el-tag :type="severityTagType(row.severity)" effect="light">
                        {{ severityLabel(row.severity) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="description" label="病情描述" min-width="260" show-overflow-tooltip />
            <el-table-column label="操作" width="160" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="openEdit(row)">编辑</el-button>
                    <el-button link type="danger" @click="removeRecord(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div style="height: 20px;"></div>

        <!-- 新增弹窗 -->
        <el-dialog v-model="addDialog" title="新增病情记录" width="520px">
            <el-form :model="form" label-width="100px">
                <el-form-item label="疾病名称">
                    <el-input v-model="form.diseaseName" placeholder="例如：上呼吸道感染" />
                </el-form-item>

                <el-form-item label="起始日期">
                    <el-date-picker v-model="form.startDate" type="date" value-format="YYYY-MM-DD"
                        placeholder="请选择开始日期" />
                </el-form-item>

                <el-form-item label="结束日期">
                    <el-date-picker v-model="form.endDate" type="date" value-format="YYYY-MM-DD" placeholder="如未痊愈可留空"
                        clearable />
                </el-form-item>

                <el-form-item label="严重程度">
                    <el-radio-group v-model="form.severity">
                        <el-radio :label="1">轻微</el-radio>
                        <el-radio :label="2">中等</el-radio>
                        <el-radio :label="3">严重</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="病情描述">
                    <el-input v-model="form.description" type="textarea" :rows="4" placeholder="简单说明症状、就诊情况、用药情况等" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="addDialog = false">取消</el-button>
                <el-button type="primary" @click="saveAdd">保存</el-button>
            </template>
        </el-dialog>

        <!-- 编辑弹窗 -->
        <el-dialog v-model="editDialog" title="编辑病情记录" width="520px">
            <el-form :model="form" label-width="100px">
                <el-form-item label="疾病名称">
                    <el-input v-model="form.diseaseName" />
                </el-form-item>

                <el-form-item label="起始日期">
                    <el-date-picker v-model="form.startDate" type="date" value-format="YYYY-MM-DD" />
                </el-form-item>

                <el-form-item label="结束日期">
                    <el-date-picker v-model="form.endDate" type="date" value-format="YYYY-MM-DD" clearable />
                </el-form-item>

                <el-form-item label="严重程度">
                    <el-radio-group v-model="form.severity">
                        <el-radio :label="1">轻微</el-radio>
                        <el-radio :label="2">中等</el-radio>
                        <el-radio :label="3">严重</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="病情描述">
                    <el-input v-model="form.description" type="textarea" :rows="4" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="editDialog = false">取消</el-button>
                <el-button type="primary" @click="saveEdit">保存</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<style scoped>
.page {
    padding: 10px;
}

/* 顶部宠物下拉选择 */
.pet-selector-row {
    display: flex;
    align-items: center;
    gap: 20px;
    padding-bottom: 16px;
}

.option-item {
    display: flex;
    align-items: center;
    gap: 10px;
}

.option-avatar {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    object-fit: cover;
}

/* 标题 + 卡片 + 按钮 */
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.header-left {
    display: flex;
    align-items: flex-start;
    gap: 16px;
}

.title {
    font-size: 20px;
    font-weight: 600;
}

/* 当前宠物卡片 */
.current-pet-card {
    display: flex;
    align-items: center;
    gap: 10px;
    background: #ffffff;
    padding: 8px 16px;
    border-radius: 12px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.06);
    border: 2px solid #409eff;
    min-width: 180px;
}

.card-avatar {
    width: 38px;
    height: 38px;
    border-radius: 8px;
    object-fit: cover;
}

.card-text {
    display: flex;
    flex-direction: column;
}

.card-name {
    font-size: 15px;
    font-weight: 600;
    color: #333;
}

.card-sub {
    font-size: 12px;
    color: #999;
    margin-top: 2px;
}

.add-record {
    align-self: center;
}

.ongoing-tag {
    color: #e6a23c;
    font-size: 12px;
    margin-left: 4px;
}
</style>
